package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Menu;
import cn.wolfcode.crm.mapper.MenuMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IMenuService;
import cn.wolfcode.crm.util.PageResult;
import cn.wolfcode.crm.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Iterator;
import java.util.List;

@Service
public class MenuServiceImpl implements IMenuService {
    @Autowired
    private MenuMapper menuMapper;


    public int insert(Menu record) {
        return menuMapper.insert(record);
    }

    public int updateByPrimaryKey(Menu record) {
        return menuMapper.updateByPrimaryKey(record);
    }

    public List<Menu> selectAll() {
        return menuMapper.selectAll();
    }

    public PageResult query(QueryObject qo) {
        int total = menuMapper.query4Count(qo);
        if (total > 0) {
            return new PageResult(total, menuMapper.query4List(qo));
        }
        return new PageResult(total, Collections.EMPTY_LIST);
    }

    public void deleteByPrimaryKey(Long id) {
        Menu menu = menuMapper.selectByPrimaryKey(id);
        deleteAllChildren(menu);
    }

    public void deleteAllChildren(Menu parent) {
        List<Menu> children = parent.getChildren();
        menuMapper.deleteByPrimaryKey(parent.getId());
        if (children.size() != 0) {
            for (Menu child : children) {
                deleteAllChildren(child);
            }
        }
    }

    public List<Menu> getRootMenu() {
        return menuMapper.getRootMenu();
    }

    public List<Menu> getEmployeeMenu() {
        Employee currentUser = UserContext.getCurrentUser();
        if(currentUser.getAdmin()){
            return getRootMenu();
        }
        List<Long> ids = menuMapper.getEmployeeMenu(currentUser.getId());
        List<Menu> allMenus = menuMapper.getRootMenu();
        checkMenu(allMenus,ids);
        return allMenus;
    }

    /**
     * 检查当前用户中所有的菜单列表,比较所有菜单和用户有的,如果所有菜单中的id在用户所有中的则不动,如果不在集合中则移除
     * @param Menus
     * @param ids
     */
    public void checkMenu(List<Menu> Menus,List<Long> ids){
        Iterator<Menu> iterator = Menus.iterator();
        while(iterator.hasNext()){
            Menu menu = iterator.next();
            //如果不在集合里面,则执行删除操作
            if(!ids.contains(menu.getId())){
                iterator.remove();
                //如果都没有它了,那么也不用继续接下来的查它子菜单的操作了
                continue;
            }
            if(menu.getChildren().size() > 0){
                checkMenu(menu.getChildren(),ids);
            }
        }
    }
}
